package com.qiche.service.impl;

import com.github.pagehelper.PageInfo;
import com.qiche.mapper.PrizeItemMapper;
import com.qiche.aspect.Result;
import com.qiche.model.*;
import com.qiche.service.PrizeItemService;
import com.qiche.service.VoucherRepositoryService;
import org.bouncycastle.asn1.x509.IetfAttrSyntax;
import org.springframework.beans.factory.annotation.Autowired;

import tk.mybatis.mapper.entity.Example;

import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 奖项服务层
 *
 * @author Linzewen
 * <p>
 * 2018年2月27日
 */
@Service("prizeItemService")
public class PrizeItemServiceImpl extends BaseService<PrizeItem> implements PrizeItemService {
    @Autowired
    private PrizeItemMapper prizeItemMapper;
    @Autowired
    private VoucherRepositoryService repositoryService;

    @Override
    public List<PrizeItemVo> selectByLuckyDrawId(Integer id) {
        return prizeItemMapper.selectByLuckyDrawId(id);
    }

    @Transactional
    @Override
    public Integer insert(PrizeItem prizeItem) {
        if (prizeItem.getPrizeType()==1){
            int count = updateRepositoryCount(prizeItem.getVoucherId(),-prizeItem.getPrizeCount(),2);
            if (count<=0){
                return 0;
            }
        }
        return save(prizeItem);
    }

    @Override
    public List<PrizeItem> selectByLuckyDrawId(Long luckyDrawId) {
        Example example = new Example(PrizeItem.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("luckyDrawId",luckyDrawId);
        criteria.andGreaterThan("prizeCount", 0);
        List<PrizeItem> prizeItem = selectByExample(example);
        return prizeItem;
    }

    public int updatePrizeCount(PrizeItem prizeItem){
        return updateNotNull(prizeItem);
    }

    @Transactional
    @Override
    public int deleteAddCount(Long id) {
        PrizeItem prizeItem = selectByKey(id);
        if (prizeItem.getPrizeType()==1){
            updateRepositoryCount(prizeItem.getVoucherId(),prizeItem.getPrizeCount(),1);
        }
        return delete(id);
    }

    /**
     *  修改 门店代金卷的数量
     * @param id 代金卷主键id
     * @param quantity 代金卷数量 正数:添加数量 负数:减少数量
     * @param type 1:增加 2:减少
     * @return
     */
    public int updateRepositoryCount(Long id,Integer quantity,int type){
        int count = 0;
        do{
            VoucherRepository repository = repositoryService.selectByKey(id);
            int num = repository.getQuantity()+quantity;
            int quantityOld = repository.getQuantity();
            if (type==2&&repository.getQuantity()<num){
                return 0;
            }
            count = repositoryService.updateQuantity(quantityOld,num,repository.getId());
        }while(count<=0);
        return count;
    }

}
